//
//  AYuComposeView.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/28.
//  Copyright © 2016年 wangce. All rights reserved.
//

import UIKit
import pop

class AYuComposeView: UIView {

    // 代表记录mainVc
    var target: UIViewController?
    
    // 保存compose
    lazy var composeButtonInfos:[AYuComposeButtonInfo] = [AYuComposeButtonInfo]()
    
    // 保存按钮数组
    lazy var buttons:[AYuComposeButton] = [AYuComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.redColor()
        // 添加控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButtons()
        // 添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    // MARK: - 监听方法
    func buttonClick(button: AYuComposeButton) {
        
        print("监听到按钮被点击了")
        // 设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            // 遍历保存按钮数组
            for value in self.buttons {
                // 设置透明度
                value.alpha = 0.2
                // 判断遍历到的按钮是否是当前点击的按钮
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 遍历保存按钮数组
                    for value in self.buttons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                        
                    }
                    }, completion: { (_) -> Void in
                        
                        guard let vcName = button.composeButtonInfo?.nextvc  else{
                            return
                        }
                        
                        
                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            return
                        }
                        
                        
                        
                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else {
                            return
                        }
                        // 初始化
                        let tempVc = cn.init()
                        let navC = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
                
        }
        
    }
    
    
    
    // MARK: - 添加composeView
    func composeViewShow(target:UIViewController){
        // 赋值
        self.target = target
        // 添加View
        target.view.addSubview(self)
        setupButtonsAnim(true)
    }
    
    
    // MARK: - 创建子控件button
    private func addChildButtons(){
        composeButtonInfos = getComposeButtonInfos()
        let childW: CGFloat = 80
        let childH: CGFloat = 100
        
        // 按钮间距
        let childMargin: CGFloat = (SCREENW - childW * 3)/4
        
        // 遍历创建
        for (i,value) in composeButtonInfos.enumerate(){
            // 得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            // 创建button
            let button = AYuComposeButton()
            // button的属性赋值
            button.composeButtonInfo = value
            // 给button添加点击事件
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.frame = CGRect(x: childMargin + (childW+childMargin)*col, y: (childH+childMargin)*row + SCREENH, width: childW, height: childH)
            addSubview(button)
            // 保存按钮
            buttons.append(button)
        }
    }
    
    // MARK: - 读取plist文件
    func getComposeButtonInfos()->[AYuComposeButtonInfo]{
        // 获取路径
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        // plist文件转数组
        let array = NSArray(contentsOfFile: file)!
        // 创建一个可变的临时数组
        var tempArray:[AYuComposeButtonInfo] = [AYuComposeButtonInfo]()
        
        // 遍历array 字典转模型
        for dic in array {
            // 创建模型
            let composeButtonInfo = AYuComposeButtonInfo(dict: dic as! [String:AnyObject])
            // 添加模型
            tempArray.append(composeButtonInfo)
        }
        return tempArray
    }
    
    
    // MARK: - 点击屏幕 view消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        setupButtonsAnim(false)
        // 延时删除当前的view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }
    
    // 设置buttons动画 (isUp==true 代表向上 显示按钮  false 代表 消失按钮)
    func setupButtonsAnim(isUp: Bool){
        // 距离
        let margin: CGFloat = isUp ? -350 : 350
        // 数组集合
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        // 遍历按钮数组 分别设置动画
        for (i,value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 10
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
            
        }
    }
    
    // MARK: - 懒加载控件
    
    // 背景磨砂图片
    private lazy var bgImageView:UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    // logo
    private lazy var logoImageView:UIImageView = UIImageView(imgName: "compose_slogan")

}









